import { createRouter, createWebHistory } from "vue-router";
import useNProgress from "@/hooks/useNProgress";
import { setRootTransitionName } from "@/utils/slide";

const NProgress = useNProgress();
//设置路由守卫，不能简单修改路由路径实现爆破
const routes = [
  {
    path: "/",
    //布局部分
    name: "layout",
    component: import("@/layout/index.vue"),
    children: [
      {
        path: "/menu",
        name: "menu",
        component: import("@/views/Menu.vue"),
        children: [
          {
            path: "/add",
            name: "add",
            component: import("@/views/Menu.vue"),
          },
        ],
      },
    ],
  },
  {
    path: "/menu",
    name: "menu",
    component: import("@/views/Menu.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: import("@/views/Login.vue"),
  },
  {
    path: "/:pathMatch(.*)*",
    name: "notfound",
    component: import("@/views/404/NotFound.vue"),
  },
];

const router = createRouter({
  //mode: 'history',
  history: createWebHistory(process.env.BASE_URL),
  routes,
});
//路由守卫
router.beforeEach((to, from, next) => {
  //开启进度条动画
  const token = localStorage.getItem("token");
  NProgress.start();
  setRootTransitionName(to, from);
  // next();
  if (to.name !== "login") {
    if (!token) {
      console.log(token);
      next({ name: "login" });
    } else {
      next();
    }
  } else {
    next();
  }
});
router.afterEach(() => {
  NProgress.done();
});
export default router;
